package cn.net.yato.picture.util.email;

import cn.net.yato.picture.entity.util.Email;
import org.springframework.stereotype.Component;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

/**
 * @ClassName EmailTools
 * @Description 实现QQ邮箱验证登录,JavaMail 版本: 1.6.0 JDK 版本: JDK 1.7 以上（必须）
 * @Author yato
 * @Date 2019/10/25 9:40
 * @Version 1.0
 *
 */
@Component
public class EmailUtil {

    /**
     * 邮件发送方法
     * @param receiveMailAccount    发送人邮箱
     */
    private void sendEmail(String receiveMailAccount, Email email){
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream("cn/net/yato/picture/util/email/email.properties");
            Properties props = new Properties();
            props.load(in);
            Session session = Session.getInstance(props);
            session.setDebug(true);
            MimeMessage message = createMimeMessage(session, props.get("mail.myemail.email").toString(),receiveMailAccount,email);
            Transport transport = session.getTransport();
            transport.connect(props.get("mail.myemail.email").toString(), props.get("mail.myemail.password").toString());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session
     *            和服务器交互的会话
     * @param sendMail
     *            发件人邮箱
     * @param receiveMail
     *            收件人邮箱
     * @return
     * @throws Exception
     */
    private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,Email email) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
        message.setFrom(new InternetAddress(sendMail, email.getSendMailName(), "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, email.getReceiveMailName(), "UTF-8"));

        // 4. Subject: 邮件主题（标题有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改标题）
        message.setSubject(email.getEmailTitle(), "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）（内容有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改发送内容）
        message.setContent(email.getEmailContent(), "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(email.getSendDate());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

    public boolean emailLogin(String sendEmail,String code,int senced){
        Email email = new Email();
        email.setEmailTitle("Picture微信小程序后台登录验证码");
        email.setReceiveMailName(sendEmail);
        email.setSendMailName("Picture Admin");
        email.setEmailContent("<h2 style='color:#151835b8;text-align: center;'>这是您的登录凭证,"+senced+"分钟内有效,如非本人操作,请忽略！</h2><p style='color:#151835b8;text-align: center;'>"+code+"</p>");
        email.setSendDate(new Date());
        try {
            sendEmail(sendEmail, email);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }
}
